package com.qfhd.soft.cjzcore.Core;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.RequiresApi;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class AppListener extends Service {
    private boolean isAppStart = false;// 判断软件是否打开，过滤重复执行
    private String packageName_now = "";//记录当前所在应用的包名
    private Context mContext;
    private Timer timer;
    private TimerTask task;
    private Handler handler_listen;
    private PendingIntent pintent;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO 自动生成的方法存根
        return null;
    }

    @Override
    public void onCreate() {
        init();
        CJLogger.v("AppListener start");
        super.onCreate();
    }

    private void init(){
        handler_listen = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    CJLogger.v("AppLister time again");
                    String packageName = null;
                    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                        packageName = getPackage();
                    }
                    else{
                        packageName = getForegroundApp();
                    }
                    //开始计时
                    CJWatcher.getInstance().beginListenApp(packageName);
                }
                super.handleMessage(msg);
            };
        };
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler_listen.sendMessage(message);
            }
        };
        timer.schedule(task, 0, CJWatcher.listenTime); //开始监听应用，每500毫秒查询一次，用这种方式循环比while更节约资源，而且更好用，这个项目刚开始用了while，把我坑坏了
    }

//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
////        flags = START_STICKY;
////        return super.onStartCommand(intent, flags, startId);
//////        Notification notification = new Notification(R.mipmap.ic_launcher, "wf update service is running", System.currentTimeMillis());
////        Notification notification = new Notification();
////        pintent= PendingIntent.getService(this, 0, intent, 0);
//////        notification.setLatestEventInfo(this, "WF Update Service", "wf update service is running！", pintent);
////
////        //让该service前台运行，避免手机休眠时系统自动杀掉该服务
////        //如果 id 为 0 ，那么状态栏的 notification 将不会显示。
////        startForeground(startId, notification);
//
//        PendingIntent notificationIntent = PendingIntent.getActivity(this, 0, intent, 0);
//        Notification noti = new Notification.Builder(this)
//                .setContentTitle("Title")
//                .setContentText("Message")
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentIntent(notificationIntent)
//                .build();
//        startForeground(123456,noti);
//        return Service.START_STICKY;
//    }

    public void onDestroy() {
        timer.cancel();//销毁服务的时候同时关闭定时器timer
        CJLogger.v("AppLister onDestroy");
        super.onDestroy();
        stopForeground(true);
        CJWatcher.getInstance().setServiceStateTop();
    }

    private String getPackage(){
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;//获取到栈顶最顶层的activity所对应的应用
        String packageName = cn.getPackageName();//从ComponentName对象中获取到最顶层的应用包名
        String className = cn.getClassName();
        CJLogger.v("packageName:"  + packageName);
        CJLogger.v("className:"  + className);
        if (!packageName_now.equals(packageName)) {//如果两个包名不相同，那么代表切换了应用
            packageName_now=packageName;//更新当前的应用包名
            isAppStart=false;//将是否是监听的应用包名的状态修改为false
        }
        if (packageName.equals("com.pandadastudio.ninjamustdie3")) {//这里举例监听QQ
//                    if (!isAppStart) {
//                        isAppStart=true;//因为一直在循环，所以需要加个isAppStart判断防止代码重复执行
//                        //。。。。逻辑处理
//                    }
            CJLogger.v("正在运行：com.pandadastudio.ninjamustdie3");
        }
        return packageName;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private String getForegroundApp() {
        UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
        long ts = System.currentTimeMillis();
        //第一个参数： 按照时间间隔来查询  第二个：开始时间 第三个：截止时间
        //通过给定的开始与结束时间  INTERVAL_BEST是按照最合适的时间间隔类型
        //还可以有：INTERVAL_DAILY  WEEKLY MONTHLY YEARLY
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);
        //返回结果中的UsageStats的官方解释是：包含特定时间范围内应用程序包的使用统计资料。
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return null;
        }

        UsageStats recentStats = null;
        for (UsageStats usageStats : queryUsageStats) {
            if (recentStats == null ||
                    recentStats.getLastTimeUsed() < usageStats.getLastTimeUsed()) {
                recentStats = usageStats;
            }
        }

//
        CJLogger.v("package:" + recentStats.getPackageName());
        return recentStats.getPackageName();
    }

}
